<script setup lang="ts">
import { computed } from 'vue'

const props = withDefaults(
  defineProps<{
    list: {
      id: number
      name: string
      price: number
      num: number
    }[]
  }>(),
  {
    list: () => []
  }
)
const emits = defineEmits<{
  (e: 'setNum', id: number, step: number): void
}>()
const total = computed<number>(() => {
  return props.list.reduce((prev, item) => {
    return prev + item.price * item.num
  }, 0)
})
</script>

<template>
  <div class="list-page">
    <div class="item">
      <div class="name">商品名</div>
      <div class="price">单价</div>
      <div class="num">数量</div>
    </div>
    <div class="item" v-for="item in list" :key="item.id">
      <div class="name">{{ item.name }}</div>
      <div class="price">{{ item.price }}</div>
      <div class="num">
        <button @click="emits('setNum', item.id, 1)">+</button>
        <span>{{ item.num }}</span>
        <button
          :disabled="item.num === 0"
          @click="emits('setNum', item.id, -1)"
        >
          -
        </button>
      </div>
    </div>
    <div class="total">总价:{{ total }}元</div>
  </div>
</template>

<style scoped>
.list-page {
  padding: 30px;
}
.item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.name {
  text-align: center;
}
.total {
  padding-top: 40px;
  text-align: right;
}
</style>
